<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=drive-width,initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="static/login.css">
<!-- font-awesome 图标字体 http://www.fontawesome.com.cn/faicons/#web-application -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" media="screen" rel="stylesheet" type="text/css">
<title>登录</title>
    <script>
function handleLogin(event) {
    event.preventDefault();  // 阻止表单默认提交
    var form = event.target;
    var formData = new FormData(form);
    var xhr = new XMLHttpRequest();
    xhr.open("POST", form.action, true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                // 登录成功，重定向
                window.location.href = "http://127.0.0.1:8080/static/menu.html";
            } else {
                // 登录失败，显示错误消息
                var error = JSON.parse(xhr.responseText);
                alert(error.message);
            }
        }
    };

    // 将表单数据转换为URL编码的字符串
    var urlEncodedData = "";
    formData.forEach((value, key) => {
        urlEncodedData += encodeURIComponent(key) + '=' + encodeURIComponent(value) + '&';
    });
    urlEncodedData = urlEncodedData.slice(0, -1);  // 移除最后一个'&'

    xhr.send(urlEncodedData);
    return false;  // 阻止表单提交
}
</script>
</head>
<body>
<form action="/login" method="post" name="login" onsubmit="return handleLogin(event)">
        <div id="login-box">
            <h1>登录</h1>
            <div class="form">
                <div class="item">
                    <i class="fa fa-user-circle-o" aria-hidden="true"></i>
                    <input type="text" name="username" placeholder="Username" id="username1" maxlength="20"required>
                </div>
                <div class="item">
                    <i class="fa fa-key" aria-hidden="true"></i>
                    <input type="password" name="password" placeholder="Password" id="password1" maxlength="20"required>
                </div>
            </div>
            <button type="submit">Login</button>
        </div>
    </div>
</form>
</body>
</html>